package com.zmn.oms.zmn.business.impl.entrust;

import com.alibaba.fastjson.JSON;
import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.common.data.common.dro.area.AreaDRO;
import com.zmn.base.common.data.dubbo.interfaces.area.AreaListRemoteService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.oms.common.constant.EntrustOrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.entrust.NewEntrustOrderDTO;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.entity.entrust.EntrustOrder;
import com.zmn.oms.model.entity.entrust.EntrustOrderQuery;
import com.zmn.oms.services.interfaces.entrust.EntrustOrderService;
import com.zmn.oms.zmn.business.interfaces.entrust.EntrustOrderBService;
import io.shardingsphere.core.keygen.DefaultKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/01/14 18:55
 */
@Slf4j
@Service("entrustOrderBService")
public class EntrustOrderBServiceImpl implements EntrustOrderBService {

    @Autowired
    DefaultKeyGenerator defaultKeyGenerator;
    @Resource
    private EntrustOrderService entrustOrderService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected AreaListRemoteService areaListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected ChannelListRemoteService channelListRemoteService;

    @Override
    public EntrustOrder prepareInsertOrder(NewEntrustOrderDTO newEntrustOrderDTO) throws OmsBaseException {
        EntrustOrder entrustOrder = new EntrustOrder();
        entrustOrder.setEntrustId(defaultKeyGenerator.generateKey().longValue());

        entrustOrder.setUserName(newEntrustOrderDTO.getUserName());
        entrustOrder.setUserPhone(newEntrustOrderDTO.getTelephone());

        entrustOrder.setCityId(newEntrustOrderDTO.getCityId());
        entrustOrder.setStreet(newEntrustOrderDTO.getStreet());
        entrustOrder.setAddress(newEntrustOrderDTO.getAddress());
        entrustOrder.setLatitude(String.valueOf(newEntrustOrderDTO.getLatitude()));
        entrustOrder.setLongitude(String.valueOf(newEntrustOrderDTO.getLongitude()));

        entrustOrder.setChannelId(newEntrustOrderDTO.getChannelId());
        entrustOrder.setChannelFromId(newEntrustOrderDTO.getChannelId());
        entrustOrder.setStatus(OrderStatusConsts.WORK_STATUS_INPUT);
        entrustOrder.setServCategId(newEntrustOrderDTO.getServCategId());
        entrustOrder.setDutyTime(newEntrustOrderDTO.getDutyTime());
        entrustOrder.setRemark(newEntrustOrderDTO.getRemark());
        entrustOrder.setTest(newEntrustOrderDTO.getTest());

        OrderProductDTO productDTO = newEntrustOrderDTO.getOrderProductList().get(0);
        entrustOrder.setProductId(productDTO.getProductId());
        entrustOrder.setProductNumber(productDTO.getNumber());

        entrustOrder.setProductName(EntrustOrderConsts.getProductName(entrustOrder.getProductId()));

        // 补全城市省份名称
        try {
            Double lng = newEntrustOrderDTO.getLongitude();
            Double lat = newEntrustOrderDTO.getLatitude();
            ResponseDTO<AreaDRO> areaDROByLatAndLng = areaListRemoteService.getAreaByLatAndLng(lng, lat);
            AreaDRO areaDRO = areaDROByLatAndLng.getData();
            log.info("AreaDRO=[{}]", JSON.toJSONString(areaDROByLatAndLng));
            if (areaDRO != null) {
                entrustOrder.setProvinceId(areaDRO.getProvinceId());
                entrustOrder.setProvinceName(areaDRO.getProvinceName());
                entrustOrder.setCityId(areaDRO.getCityId());
                entrustOrder.setCityName(areaDRO.getCityName());
                entrustOrder.setCountyId(areaDRO.getCountyId());
                entrustOrder.setCountyName(areaDRO.getCountyName());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        // 补全来源渠道名称
        try {
            ResponseDTO<ChannelDRO> channelResp = channelListRemoteService.getByChannelId(newEntrustOrderDTO.getChannelId());
            ChannelDRO channelDRO = channelResp.getData();
            log.info("ChannelDRO=[{}]", JSON.toJSONString(channelDRO));
            if (channelDRO != null) {
                entrustOrder.setChannelFromName(channelDRO.getName());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        entrustOrder.setCreater(newEntrustOrderDTO.getOperator());
        entrustOrder.setCreaterId(newEntrustOrderDTO.getOperatorId());
        entrustOrder.setCreaterDeptId(newEntrustOrderDTO.getDeptId());
        entrustOrder.setCreaterDeptName(newEntrustOrderDTO.getDeptName());

        // 委派渠道默认设置为蚂蚁修
        entrustOrder.setChannelToId(900001);
        entrustOrder.setChannelToName("蚂蚁修");

        return entrustOrder;
    }

    @Override
    @Transactional
    public ResultDTO<EntrustOrder> doInsertOrder(EntrustOrder entrustOrder) {
        entrustOrderService.insertEntrustOrder(entrustOrder);
        return ResultDTO.success(entrustOrder);
    }

    @Override
    public ResultDTO<List<EntrustOrder>> listOrders(EntrustOrderQuery query) throws OmsBaseException {
        List<EntrustOrder> entrustOrders = entrustOrderService.listOrders(query);
        if (entrustOrders == null) {
            entrustOrders = new LinkedList<>();
        }
        return ResultDTO.success(entrustOrders);
    }

    @Override
    public ResultDTO<EntrustOrder> findById(Long entrustId) throws OmsBaseException {
        EntrustOrder entrustOrder = entrustOrderService.findByKey(entrustId);

        if (entrustOrder == null) {
            return ResultDTO.fail("订单不存在");
        }

        return ResultDTO.success(entrustOrder);
    }

    @Override
    @Transactional
    public ResultDTO updateById(EntrustOrder entrustOrder) throws OmsBaseException {
        int i = entrustOrderService.updateByKey(entrustOrder);
        return i > 0 ? ResultDTO.success() : ResultDTO.fail("没有记录被修改");
    }
}
